#include "singleapplication.h"
#include "definitions.h"
#include <QtDebug>
#ifndef HAVE_DBUS
#include <QMessageBox>
#else
#include <QtDBus>
#endif


SingleApplication::SingleApplication(int &argc, char *argv[], const QString uniqueKey)
    : QApplication(argc, argv),
      _uniqueKey(uniqueKey)
{
    sharedMemory.setKey(_uniqueKey);

    if (sharedMemory.attach()) {
        _isRunning = true;
#ifdef HAVE_DBUS
        qDebug() << QString("%1Another instance is running already. Notifying it.").arg(APP_ID);
        QDBusInterface dbus(DBUS_SERVICE, DBUS_PATH, DBUS_INTERFACE, QDBusConnection::sessionBus());
        if (!dbus.isValid())
        {
            qWarning() << "dbusCall: QDBusInterface is invalid";
            return;
        }
        QDBusMessage msg = dbus.call("raise");
        if (!msg.errorName().isEmpty())
            qDebug() << msg.errorMessage();
#else
        QMessageBox::information(0, tr("RSSGuard is running already"),
                                 tr("Another instance of RSSGuard is already running."));
#endif
    }
    else {
        _isRunning = false;
        // create shared memory.
        if (!sharedMemory.create(1)) {
            qDebug() << QString("%1Unable to create single instance.").arg(APP_ID);
            return;
        }
    }
}

bool SingleApplication::isRunning() {
    return _isRunning;
}
